/**
 * 考勤管理-外出记录
 */
import React, { useEffect, useRef } from 'react';
import { connect } from 'umi';
import { Link, router } from 'umi';
import { Form, Input, Button, Table, Card } from 'antd';
import moment from 'moment';
import { QuickForm, utils } from 'vv-frontend-components';
import DateRange from '@/components/DateRange';
import { CompanyDepartPlus } from '@/containers';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import LinkTo from '@/components/LinkTo';
import { dateConversion2, download } from '@/utils/utils';
import Locale from '@/utils/locale';
import AuthComponent from '@/utils/auth/AuthComponent';
import AuthCode from '@/utils/auth/AuthCode';
import { withRoutePage } from '@/utils/enhanceUtils';
import { Pagination } from '@/components';

import styles from './index.less';

const { locale } = new Locale('stat.overtime');
const { deepTrim } = utils;

const ORDER_MAP = { asc: 'ascend', desc: 'descend' };

const List = ({ activeKey, form, overbusinessrecords, loading, dispatch, route, location }) => {
    const { query } = location;
    const { getFieldsValue } = form;
    const { outsidePagination: pagination, outsideList: data, osOrder } = overbusinessrecords;
    const { authCode } = new AuthCode(route.code);
    const [sorter, setSorter] = React.useState('');

    const getSearchData = () => {
        const { companyDepart = {}, date = { range: [] }, userName } = getFieldsValue();
        const payload = {
            companyCode: companyDepart?.companyId || '',
            departmentCode: companyDepart?.departmentId || '',
            startTime: date.range[0] ? date.range[0].format('YYYY-MM-DD') : '',
            endTime: date.range[1] ? date.range[1].format('YYYY-MM-DD') : '',
            employeeName: userName || '',
            orderByField: osOrder,
            dateType: date.type,
            pageNo: query.pageNo || 1,
            pageSize: query.pageSize || 10
        };
        return payload;
    };

    const transformSortOrder = (currentField = '') => {
        // 兼容服务端数据与 antd 的 sortOrder 参数
        const [field, order] = osOrder.split(' ');
        if (currentField !== field || !ORDER_MAP[order]) {
            return false;
        }
        return ORDER_MAP[order];
    };

    const fetchList = () => {
        dispatch(
            deepTrim({
                type: 'overbusinessrecords/fetchOutsideList',
                payload: getSearchData()
            })
        );
    };

    const handleExport = () => {
        const { pageNo, pageSize, ...other } = getSearchData();
        download({
            getData: () =>
                dispatch({
                    type: 'overbusinessrecords/fetchOutsideExport',
                    payload: deepTrim(other)
                })
        });
    };

    const config = [
        {
            field: 'companyDepart',
            label: '机构',
            component: <CompanyDepartPlus />
        },
        {
            field: 'userName',
            label: '员工',
            config: {
                initialValue: query.employeeName || ''
            },
            component: <Input placeholder="输入姓名" />
        },
        {
            field: 'date',
            config: {
                initialValue: {
                    range: [
                        query.startTime ? moment(query.startTime) : moment().startOf('month'),
                        query.endTime ? moment(query.endTime) : moment()
                    ],
                    type: query.dateType || 'month'
                }
            },
            component: (
                <DateRange
                    range
                    type="month"
                    dateTypes={[
                        {
                            label: '本周',
                            type: 'week'
                        },
                        {
                            label: '本月',
                            type: 'month'
                        },
                        {
                            label: '本年',
                            type: 'year'
                        }
                    ]}
                />
            )
        },
        {
            component: (
                <div>
                    <Button type="primary" htmlType="submit">
                        {locale('form.search', false)}
                    </Button>
                    <AuthComponent code={authCode('export')}>
                        <Button
                            style={{ marginLeft: '5px' }}
                            onClick={handleExport}
                            disabled={loading.effects['overbusinessrecords/fetchOutsideList']}
                        >
                            导出
                        </Button>
                    </AuthComponent>
                </div>
            )
        }
    ];

    const columns = [
        {
            title: '工号',
            dataIndex: 'userNo',
            key: 'userNo'
        },
        {
            title: '姓名',
            dataIndex: 'userName',
            key: 'userName',
            width: 90
        },
        {
            title: '组织机构',
            dataIndex: 'departName',
            key: 'departName',
            render: text => (
                <div className={styles.ellipsis} title={text}>
                    {text}
                </div>
            )
        },
        {
            title: '开始时间',
            dataIndex: 'startTime',
            key: 'startTime',
            sorter: () => {},
            width: 180,
            sortOrder: transformSortOrder('start_time'),
            render(text, record) {
                if (record.startTime === '') {
                    return <span>--</span>;
                }
                return <span>{record.startTime}</span>;
            }
        },
        {
            title: '结束时间',
            dataIndex: 'endTime',
            key: 'endTime',
            width: 180,
            sortOrder: transformSortOrder('end_time'),
            sorter: () => {},
            render(text, record) {
                if (record.endTime === '') {
                    return <span>--</span>;
                }
                return <span>{record.endTime}</span>;
            }
        },
        {
            title: '时长',
            dataIndex: 'outLong',
            key: 'outLong',
            width: 150,
            sortOrder: transformSortOrder('out_long'),
            sorter: () => {},
            render(text) {
                return <span>{text === '' ? '--' : dateConversion2(text)}</span>;
            }
        },
        {
            title: '事由',
            dataIndex: 'outReason',
            key: 'outReason',
            render: text => (
                <p
                    style={{
                        width: '150px',
                        whiteSpace: 'nowrap',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        marginBottom: '0'
                    }}
                    title={text}
                >
                    {text === '' ? '--' : text}
                </p>
            )
        },
        {
            title: '相关流程',
            dataIndex: 'applicationNo',
            key: 'applicationNo',
            width: 300,
            render(text, record) {
                const { applicationNo } = record;
                const isOldFlow = !applicationNo.includes('-'); // 新旧流程跳转差异判断
                const url = isOldFlow
                    ? '/office/institutions/flowManage/fullApprovalProcess/processDetail'
                    : '/personal/portal/myAuditRead/myAuditReadDetail';
                const params = isOldFlow ? { applicationNo: record.applicationNo, linkFrom: '1' } : { applicationNo };
                return (
                    <span>
                        {record.applicationNo ? (
                            <LinkTo to={url} query={params}>
                                {record.applicationNo}
                            </LinkTo>
                        ) : (
                            '--'
                        )}
                    </span>
                );
            }
        },
        {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            width: 100,
            fixed: 'right',
            render(text, record) {
                return record.status === 0 ? (
                    '--'
                ) : (
                    <Link
                        to={{
                            pathname: '/office/personnelManagement/attendance/timetag/attendRecord/clockRecord',
                            query: {
                                id: record.employeeCode,
                                name: record.userName,
                                startTime: record.startTime,
                                endTime: record.endTime
                            }
                        }}
                    >
                        打卡记录
                    </Link>
                );
            }
        }
    ];

    const tableChange = (newPagination, filters, sorters) => {
        let orderBy;
        let sorterField;
        const returnOrderBy = s => {
            if (sorters.field === 'startTime') {
                sorterField = 'start_time';
            }
            if (sorters.field === 'endTime') {
                sorterField = 'end_time';
            }
            if (sorters.field === 'outLong') {
                sorterField = 'out_long';
            }
            const order = s.order.trim().split('end')[0];
            orderBy = `${sorterField} ${order}`;
        };
        if (sorters && sorters.field && sorters.order) {
            returnOrderBy(sorters);
        } else if (typeof sorters === 'string') {
            orderBy = '';
        }

        if (sorters && sorter !== sorters) {
            setSorter(sorters);
            if (sorters && sorters.field && sorters.order) {
                returnOrderBy(sorters);
            } else if (typeof sorters === 'string') {
                orderBy = '';
            }
            dispatch({
                type: 'overbusinessrecords/save',
                payload: {
                    osOrder: orderBy || ''
                }
            });
        }
        history.push({ query: { ...query, pageNo: 1 } });
    };

    const isFirstRun = useRef(true);

    useEffect(() => {
        fetchList();
    }, []);

    // 每当分页数或页数改变时均应该重新请求表格数据
    useEffect(() => {
        // 第一次不运行
        if (isFirstRun.current) {
            isFirstRun.current = false;
            return;
        }
        fetchList();
    }, [activeKey, overbusinessrecords.osOrder, query.pageNo, query.pageSize]);

    const handelPagination = _pagination => {
        history.push({ query: { ...query, pageNo: _pagination.current, pageSize: _pagination.pageSize } });
    };

    return (
        <PageHeaderWrapper>
            <Card>
                <Form
                    layout="inline"
                    style={{ marginBottom: 15 }}
                    onSubmit={e => {
                        e.preventDefault();
                        history.push({ query: { ...getSearchData(), pageNo: 1 } });
                        fetchList();
                    }}
                >
                    <QuickForm form={form} config={config} />
                </Form>
                <Table
                    bordered={false}
                    columns={columns}
                    loading={loading.models.overbusinessrecords}
                    dataSource={data}
                    rowKey="id"
                    onChange={tableChange}
                    pagination={false}
                    scroll={{ x: 'max-content' }}
                />
                <Pagination
                    onChange={handelPagination}
                    total={pagination.total}
                    current={query.pageNo}
                    pageSize={query.pageSize}
                    loading={loading.models.overbusinessrecords}
                />
            </Card>
        </PageHeaderWrapper>
    );
};

export default withRoutePage(
    connect(({ overbusinessrecords, loading }) => ({ overbusinessrecords, loading }))(Form.create()(List))
);
